package com.mall.order.mq.order;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;

/*
 * @description: 延时消息生成者
 */
@Slf4j
@Component
public class DelayOrderProducer {

    private DefaultMQProducer mqProducer;

    //组件初始化的时候将初始化这个消息生产者
    @PostConstruct
    public void init() {
        mqProducer = new DefaultMQProducer("delay_order_producer");
        mqProducer.setNamesrvAddr("127.0.0.1:9876");

        try {
            mqProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    //发送消息的方法
    public boolean sendOrderDelayMessage(String orderId, int delayTimeLevel) {

        try {
            byte[] orderIdBytes = orderId.getBytes("utf-8");
            Message message = new Message("delay_order_cancel", orderIdBytes);
            //10s（3） 30s 1m 2m
            message.setDelayTimeLevel(delayTimeLevel);
            SendResult sendResult = mqProducer.send(message);

            if (SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
                return true;
            }
            log.error("发送消息未得到处理");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        }
        return false;
    }

}
